package com.example.cdctravel

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.cdctravel.MyAdapter.InnerHolder

class MyAdapter(private val context: Context) : RecyclerView.Adapter<InnerHolder>() {
    private val mData: MutableList<PlaceBean>? = ArrayList()
    private var mOnItemClickListener: OnItemClickListener? = null
    fun setNewData(data: List<PlaceBean>?) {
        mData!!.clear()
        mData.addAll(data!!)
        notifyDataSetChanged()
    }

    fun getmData(): List<PlaceBean>? {
        return mData
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InnerHolder {
        val view = View.inflate(parent.context, R.layout.item_stagger, null)
        return InnerHolder(view)
    }

    fun setOnItemClickListener(mOnItemClickListener: OnItemClickListener?) {
        this.mOnItemClickListener = mOnItemClickListener
    }

    interface OnItemClickListener {
        fun onItemClick(view: View?, position: Int)
    }

    override fun onBindViewHolder(holder: InnerHolder, position: Int) {
        holder.setData(mData!![position])
        if (mOnItemClickListener != null) {
            //为ItemView设置监听器
            holder.itemView.setOnClickListener {
                val position = holder.layoutPosition // 1
                mOnItemClickListener!!.onItemClick(holder.itemView, position) // 2
            }
        }
    }

    override fun getItemCount(): Int {
        //返回条目个数
        return mData?.size ?: 0
    }

    inner class InnerHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val mTitle: TextView
        private val mIcon: ImageView

        init {
            mTitle = itemView.findViewById<View>(R.id.title) as TextView
            mIcon = itemView.findViewById<View>(R.id.icon) as ImageView
        }

        fun setData(itemBean: PlaceBean) {
            mTitle.text = itemBean.name
            mIcon.setImageResource(getDrawableId(context, itemBean.pic))
        }
    }

    companion object {
        fun getDrawableId(context: Context, `var`: String?): Int {
            return try {
                context.resources.getIdentifier(`var`, "mipmap", context.packageName)
            } catch (e: Exception) {
                0
            }
        }
    }
}
